package com.crack.nga2.span;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.text.style.DynamicDrawableSpan;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.View;

import java.lang.ref.WeakReference;

/**
 * TextView中的图片点击事件
 * Created by lenovo on 2015/12/30.
 */
public class ClickableImageSpan extends ImageSpan {
    int start;
    int end;
    private Drawable drawable;
    private String source;

    public ClickableImageSpan(Drawable d) {
        this(d, null);
    }

    public ClickableImageSpan(Drawable d, String source) {
        this(d, source, ALIGN_BOTTOM);
    }

    public ClickableImageSpan(Drawable d, String source, int verticalAlignment) {
        super(null, source, verticalAlignment);
        this.drawable = d;
        this.source = source;
    }

    public void setDrawable(Drawable drawable) {
        mDrawableRef = null;
        this.drawable = drawable;
    }

    @Override
    public Drawable getDrawable() {
        return drawable;
    }

    public String getSource() {
        return source;
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        Drawable b = getCachedDrawable();
        canvas.save();
        int transY = bottom - b.getBounds().bottom;
        if (mVerticalAlignment == ALIGN_BASELINE) {
            transY -= paint.getFontMetricsInt().descent;
        }

        canvas.translate(x, transY);
        b.draw(canvas);
        canvas.restore();
    }

    private Drawable getCachedDrawable() {
        WeakReference<Drawable> wr = mDrawableRef;
        Drawable d = null;

        if (wr != null)
            d = wr.get();

        if (d == null) {
            d = getDrawable();
            mDrawableRef = new WeakReference<Drawable>(d);
        }

        return d;
    }

    private WeakReference<Drawable> mDrawableRef;

    public void onClick(View view) {

    }
}
